package com.sinog.front.controller.basic;

import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.basic.RoleResService;
import com.sinog.front.feign.basic.UserService;
import com.sinog.front.service.user.UserFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 角色资源管理
 * @author -
 * @date -
 */
@RestController
public class RoleResController {

    @Autowired
    private RoleResService roleResService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserFacade service;

    /**
     * 获取角色资源列表
     * @param roleid roleid
     * @return String
     */
    @GetMapping("/role/resource/tree")
    public String getRoleResourcesTree(String roleid) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Result result1 = userService.selectOne(authentication.getName(),"0");
        UserDTO userDTO;
        if(Constants.Number.NUM_ONE.equals(result1.getCode())) {
            String data = (String) result1.getData();
            userDTO = JsonUtil.toBean(data, UserDTO.class);
        } else {
            userDTO = new UserDTO();
        }
        String roleid1 = userDTO.getRoleid();
        if(Constants.RoleId.ROLE_ID_AB.equals(roleid1)) {
            return roleResService.getRoleResourcesTree(roleid);
        }
        return "";
    }

    /**
     * 保存角色资源列表
     * @param request request
     * @param resids resids
     * @param roleid roleid
     * @return Result
     */
    @Log(type = "更新", value = "更新角色资源")
    @PostMapping("/role/resource")
    public Result saveRoleResources(HttpServletRequest request,
                                    @RequestParam(defaultValue = "-1") String resids,@RequestParam String roleid) {
        UserDTO authentication = service.getAuthentication();
        String roleid1 = authentication.getRoleid();
        Map<String,String> resMap = new HashMap<>(16);
        resMap.put("resids",resids);
        if(Constants.RoleId.ROLE_ID_AB.equals(roleid1)) {
            return roleResService.saveRoleResources(resMap,roleid,authentication.getUsername());
        }
        return Result.failure(ReturnCode.NO_PERMISSION);
    }
}